package yunquan.wang.modules.base.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import yunquan.wang.base.config.AppConfig;
import yunquan.wang.base.dao.PropertyFilter;
import yunquan.wang.base.utils.DateTimeUtils;
import yunquan.wang.base.web.WebConstants;
import yunquan.wang.base.web.WebHelper;
import yunquan.wang.base.web.ajax.AjaxDone;
import yunquan.wang.modules.base.entity.BackupDatabase;
import yunquan.wang.modules.base.service.BackupDatabaseService;

@Controller
@RequestMapping("/core/backupdata")
public class DatabaseBakController   {
	@Resource
	private BackupDatabaseService service;

	 @RequestMapping(value = "/list.do")
	 public String list(HttpServletRequest request, Model model) {
		Pageable page = WebHelper.getPage(request);
		List<PropertyFilter> filters = WebHelper.filterRequest(request);
		model.addAttribute(WebConstants.ATTRIBUTE_PAGE,service.findPage(page, filters));
			return "core/bakupList";
		}

		@RequestMapping(value = "/save.do")
		public @ResponseBody AjaxDone save (@Valid BackupDatabase entity,	BindingResult bindingResult) {
			if (bindingResult.hasErrors()) {
				return WebHelper.validFail(bindingResult);
			} else {
				try {
					service.backUpdataAll(entity.getBackName());
				} catch (Exception e) {
				return	WebHelper.saveFail( e);
				}
			}
			return WebHelper.saveSuccess();
		}
		
 

		@RequestMapping(value = "/delete.do")
		public @ResponseBody AjaxDone delete(String [] id) {
			for(String ids:id){
			service.delete(ids);
			}
		return	WebHelper.deleteSuccess();
		}

	/**
	 * 输入更改
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/input.do")
	public String input(String id,Model model) {
		BackupDatabase entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = service.get(id);
		} else {
			entity = new BackupDatabase();
		}
		model.addAttribute(WebConstants.ATTRIBUTE_ENTITY, entity);
		return "core/bakInput";
	}

	@RequestMapping(value = "/restore.do")
	public @ResponseBody  AjaxDone restore(String id) {
		service.restoreData(id);
		 AjaxDone done=	WebHelper.deleteSuccess();
		 done.setMessage("恢复成功！");
		 return done;
	}

	@RequestMapping(value = "/upload.do")
	public String upload() {
 
		return "core/bakUpload";
	}
	@RequestMapping(value = "/down.do")
 public void donwload(String id,HttpServletResponse response)
 {
		try {
		BackupDatabase	entity = service.get(id);
		 response.setCharacterEncoding("utf-8");
	      response.setContentType("multipart/form-data");
	     response.setHeader("Content-Disposition", "attachment;fileName="+entity.getBackName());
	 String filePath=    AppConfig.getBackDbFilePath() + File.separator+entity.getFileName();
			  InputStream inputStream = new FileInputStream(filePath);
        OutputStream os=response.getOutputStream();
        byte[] b=new byte[1024];
        int length;
        while((length=inputStream.read(b))>0){
            os.write(b,0,length);
        }
        inputStream.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 }

	@RequestMapping(value = "/updata.do")
	public @ResponseBody  AjaxDone updata(MultipartFile upFile, String bakName) {
		String dateTime = DateTimeUtils
				.getCurrentDateString(DateTimeUtils.SSFORMARTSTRING);
		File backPath = new File(AppConfig.getBackDbFilePath());
		if (!backPath.exists()) {
			backPath.mkdir();
		}
		String filepath = AppConfig.getBackDbFilePath() + File.separator
				+ dateTime + ".zip";

		File des = new File(filepath);
		try {
			upFile.transferTo(des);

		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Long size = des.length() / 1024;
		BackupDatabase bak = new BackupDatabase();
		bak.setBackName(bakName);
		bak.setFilesize(size.intValue());
		bak.setSuccess(true);
		bak.setFileName(dateTime + ".zip");
		service.save(bak);
		AjaxDone done=new AjaxDone();
		done.setStatusCode(AjaxDone.STATUS_OK);
		 done.setMessage("上传成功！");
		 return done;
	}
}
